package com.lch.webdemo.wxhandler;


import com.lch.webdemo.common.enums.MenuClickMsgEnum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpKefuServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 点击菜单事件
 *
 * @author liuchenhui
 */
@Component
@Slf4j
public class MenuHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        WxMpKefuService kfService = new WxMpKefuServiceImpl(wxMpService);

        try {
            // 点击事件
            String key = wxMessage.getEventKey();
            String openId = wxMessage.getFromUser();
            MenuClickMsgEnum menuClick = MenuClickMsgEnum.findMenuByKey(key);
            if (menuClick == null) {
                return null;
            }
            sendTxtAndImgToUser(menuClick, openId, kfService);
        } catch (WxErrorException e) {
            log.error("菜单事件处理失败", e);
        }

        return null;
    }

    // 发送消息
    private void sendTxtAndImgToUser(MenuClickMsgEnum menuClick, String openId, WxMpKefuService kfService) throws WxErrorException {
        // 如果获取图片
        if (menuClick.getType().equals("image")) {
            WxMpKefuMessage imgMessage = WxMpKefuMessage.IMAGE().mediaId(menuClick.getContent()).toUser(openId).build();
            kfService.sendKefuMessage(imgMessage);
        }
        // 如果是回复文字直接回复文字
        else if (menuClick.getType().equals("text")) {
            WxMpKefuMessage textMessage = WxMpKefuMessage.TEXT().content(menuClick.getContent()).toUser(openId).build();
            kfService.sendKefuMessage(textMessage);
        }
    }
}
